package com.nep.NEPM.controller;

import com.nep.entity.administrator.User;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.stage.Stage;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.time.LocalDate;

import static com.nep.common.util.AlertUtil.showError;
import static com.nep.common.util.AlertUtil.showInfo;
import static com.nep.common.util.SceneSwitcherUtil.switchScene;

public class SupervisorLocalViewController {
    @FXML
    private Button btn_OUT;
    @FXML
    private Button btn_Back;
    @FXML
    private Label lblId;          // 编号
    @FXML
    private Label lblName;        // 姓名
    @FXML
    private Label lblProvince;    // 省份
    @FXML
    private Label lblCity;        // 城市
    @FXML
    private Label lblGrade;       // 污染等级
    @FXML
    private Label lblDate;        // 日期
    @FXML
    private Label lblTime;        // 时间
    @FXML
    private Label lblPhone;
    @FXML
    private Label lblAddress;
    @FXML
    private Label lblDescription;
    @FXML
    private Label lblSex;
    @FXML
    private Label lblBornDate;
    @FXML
    private Label lblDegree;
    @FXML
    private ComboBox<String> cmbLocalAssign;
    @FXML
    private CheckBox chkAllopatric;
    @FXML
    private Button btnLocalAssign;

    private SupervisorListViewController parentController;

    private static final String ASSIGNMENT_DIR = "assignments/";
    private static final String LOCAL_ASSIGNMENT_FILE = "local_assignments.txt";

    // 初始化视图数据的方法
    public void initData(User user, SupervisorListViewController parentController) {
        this.parentController = parentController;
        setUserInfoToLabels(user);
        setupComboBox();
        setupAllopatricCheckbox(user);
    }

    // 将用户信息设置到标签上
    private void setUserInfoToLabels(User user) {
        lblPhone.setText(user.getPhone());
        lblAddress.setText(user.getAddress());
        lblDescription.setText(user.getDescription());
        lblSex.setText(user.getSex());
        lblBornDate.setText(user.getBornDate());
        lblDegree.setText(user.getDegree());
        lblId.setText(user.getId());
        lblName.setText(user.getName());
        lblProvince.setText(user.getProvince());
        lblCity.setText(user.getCity());
        lblGrade.setText(user.getGrade());
        lblDate.setText(user.getDate());
        lblTime.setText(user.getTime());
    }

    // 设置下拉框选项
    private void setupComboBox() {
        ObservableList<String> localWorkers = FXCollections.observableArrayList(
                "网格员1", "网格员2", "网格员3", "网格员4"
        );
        cmbLocalAssign.setItems(localWorkers);
    }

    // 设置异地抽派复选框事件
    private void setupAllopatricCheckbox(User user) {
        chkAllopatric.selectedProperty().addListener((obs, oldVal, newVal) -> {
            if (newVal) {
                try {
                    openAllopatricView(user);
                } catch (IOException e) {
                    showError("错误", "加载异地抽派界面失败: " + e.getMessage());
                    chkAllopatric.setSelected(false);
                }
            }
        });
    }

    // 打开异地抽派视图
    private void openAllopatricView(User user) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader();
        URL url = getClass().getResource("/com/nep/NEPM/view/SupervisorAllopatricView.fxml");
        fxmlLoader.setLocation(url);
        Parent root = fxmlLoader.load();

        SupervisorAllopatricViewController controller = fxmlLoader.getController();
        controller.initData(user, parentController); // 传递父控制器

        Stage stage = new Stage();
        stage.setScene(new Scene(root));
        stage.setTitle("异地抽派 - " + user.getName());
        stage.show();
    }

    @FXML
    private void LocalAssign(ActionEvent event) {
        String worker = cmbLocalAssign.getValue();
        if (worker == null) {
            showError("警告", "请选择网格员");
            return;
        }

        String assignmentInfo = createAssignmentInfo(worker);
        saveAssignmentToFile(LOCAL_ASSIGNMENT_FILE, assignmentInfo);

        if (parentController != null) {
            parentController.updateUserAssignmentStatus(lblId.getText(), true);
        }

        showInfo("成功", "本地指派任务已保存");
        closeCurrentWindow();
    }

    // 创建任务信息字符串
    private String createAssignmentInfo(String worker) {
        return String.format(
                "本地指派任务\n" +
                        "编号: %s\n姓名: %s\n省份: %s\n城市: %s\n" +
                        "污染等级: %s\n日期: %s\n时间: %s\n" +
                        "联系电话: %s\n地址: %s\n描述: %s\n" +
                        "性别: %s\n出生日期: %s\n学历: %s\n" +
                        "指派给: %s\n指派时间: %s\n\n",
                lblId.getText(), lblName.getText(), lblProvince.getText(), lblCity.getText(),
                lblGrade.getText(), lblDate.getText(), lblTime.getText(),
                lblPhone.getText(), lblAddress.getText(), lblDescription.getText(),
                lblSex.getText(), lblBornDate.getText(), lblDegree.getText(),
                worker, LocalDate.now()
        );
    }

    private void saveAssignmentToFile(String filename, String content) {
        try {
            ensureDirectoryExists();
            Files.write(
                    Paths.get(ASSIGNMENT_DIR + filename),
                    content.getBytes(StandardCharsets.UTF_8),
                    StandardOpenOption.CREATE, StandardOpenOption.APPEND
            );
        } catch (IOException e) {
            showError("错误", "保存指派信息失败: " + e.getMessage());
        }
    }

    // 确保目录存在
    private void ensureDirectoryExists() {
        new File(ASSIGNMENT_DIR).mkdirs();
    }

    // 关闭当前窗口
    private void closeCurrentWindow() {
        ((Stage) btnLocalAssign.getScene().getWindow()).close();
    }

    public void OUT(ActionEvent actionEvent) {
        switchScene(btn_OUT, "/com/nep/NEPM/view/IndexView.fxml");
    }

    public void Back(ActionEvent actionEvent) {
        switchScene(btn_Back, "/com/nep/NEPM/view/SupervisorListView.fxml");
    }
}